package com.guanzi.netty.server.handler;

import com.guanzi.netty.server.session.Session;
import com.guanzi.netty.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 管子
 * @date 2025/3/13 21:44
 * @description: QuitHandler 类
 */
@ChannelHandler.Sharable
public class QuitHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(QuitHandler.class);

    /**
     * 正常断开
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 去掉离线的channel，设置为离线
        Channel channel = ctx.channel();
        Session session = SessionFactory.getSession();
        session.unbind(channel);
        log.info("{} 已经断开连接", channel);
    }

    /**
     * 异常断开
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        Session session = SessionFactory.getSession();
        session.unbind(channel);
        log.info("{} 已经异常断开连接， 异常是: {}", channel, cause.getMessage());
    }
}
